iT邦幫忙

0

C#轉換 某日是今年第幾天/第幾週

  • 分享至 

  • xImage
  •  

加入using System.Globalization;
測試時請把參數d改成"yyyyMMdd"格式,例如"20230614"
主要轉換屬性為DateTime.DayOfYear及GregorianCalendar.GetWeekOfYear()

1.天數

DateTime date = DateTime.ParseExact("20240229", "yyyyMMdd", CultureInfo.InvariantCulture);
int day = date.DayOfYear;
Console.WriteLine(day);

2.週數

public static int W(string d)
{
    DateTime date = DateTime.ParseExact(d, "yyyyMMdd", CultureInfo.InvariantCulture);
    int week = GetWeekOfYear(date);
    return week;
}
private static int GetWeekOfYear(DateTime dt)
{
    GregorianCalendar gc = new GregorianCalendar();
    return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言